package com.demo.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.demo.exception.ServiceException;
import org.springframework.stereotype.Component;

import java.util.Date;

//jwt工具类
@Component
public class JWTUTIL {

    //过期时间 设置为5个小时 redis设置为3个小时 如果解析失败或者redis不存在 就重新登录
    private static final long time = 500 * 60 * 1000;

    private static final String tokenSECRET = "Fkey";

    //生成token
    public static String getToken(Long uid, String username) {
        Date date = new Date(System.currentTimeMillis() + time);
        //秘钥 个人信息
        String token = JWT.create().withClaim("id", uid).withClaim("username", username).withIssuedAt(new Date()).withExpiresAt(date).sign(Algorithm.HMAC256(tokenSECRET));
        return token;
    }

    //验证token是否合法
    public static Boolean verify(String token){
        Boolean result=false;
       JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(tokenSECRET)).build();
       DecodedJWT decodedJWT=null;
           decodedJWT=jwtVerifier.verify(token);
            Long Uid=decodedJWT.getClaim("id").asLong();
           String username=decodedJWT.getClaim("username").asString();
            if(Uid!=null&&username.length()>0){
                result=true;
            }
       return result;
    }


    //获取token中的信息
    public static String tokenInfo(String token){
        String result=" ";
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(tokenSECRET)).build();
        DecodedJWT decodedJWT=null;

        try{
            decodedJWT=jwtVerifier.verify(token);
            result=decodedJWT.getClaim("username").asString();
        }catch (Exception e){
            throw new ServiceException("token解析失败");
        }
        return result;
    }


    //获取token中的用户uid
    public static Long getUserUidByToken(String token){
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(tokenSECRET)).build();
        DecodedJWT decodedJWT=null;
        decodedJWT=jwtVerifier.verify(token);
        Long Uid=decodedJWT.getClaim("id").asLong();
        return  Uid;
    }

}
